package com.mrd.gtimpframe.service.impl;

import com.mrd.framework.config.web.json.Result;
import com.mrd.gtimp.base.entity.Company;
import com.mrd.gtimp.business.entity.RegisteredCompany;
import com.mrd.gtimpframe.entity.AgentRef;
import com.mrd.gtimpframe.entity.Attachment;
import com.mrd.gtimpframe.entity.AuditInfo;
import com.mrd.gtimpframe.entity.CompanyAttachment;
import com.mrd.gtimpframe.entity.CompanyInfo;
import com.mrd.gtimpframe.entity.SuperCompanyInfo;
import com.mrd.gtimpframe.entity.TGenComContact;
import com.mrd.gtimpframe.repository.CompanyInfoMapper;
import com.mrd.gtimpframe.repository.TGenComContactMapper;
import com.mrd.gtimpframe.repository.UserMapper;
import com.mrd.gtimpframe.service.AgentRefService;
import com.mrd.gtimpframe.service.AttachmentService;
import com.mrd.gtimpframe.service.ComAuditService;
import com.mrd.gtimpframe.service.CompanyAttachmentService;
import com.mrd.gtimpframe.service.CompanyInfoService;
import com.mrd.gtimpframe.service.UserService;
import com.mrd.util.LoginUtil;
import com.mrd.util.StringUtils;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;

/**
 * @author dusy
 */
@Service
public class CompanyInfoServiceImpl implements CompanyInfoService {

    @Resource
    private CompanyInfoMapper companyInfoMapper;
    @Resource
    private AgentRefService agentRefService;
    @Resource
    private ComAuditService comAuditService;
    @Resource
    private CompanyAttachmentService companyAttachmentService;
    @Resource
    private TGenComContactMapper tGenComContactMapper;
    @Resource
    private AttachmentService attachmentService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserService userService;

    @Override
    public int deleteByPrimaryKey(Object id) {
        return companyInfoMapper.deleteByPrimaryKey((String) id);
    }

    @Override
    public int insert(Object o) {
        return companyInfoMapper.insert((CompanyInfo) o);
    }

    @Override
    public int insertSelective(Object o) {
        return companyInfoMapper.insertSelective((CompanyInfo) o);
    }

    @Override
    public Object selectByPrimaryKey(Object id) {
        return companyInfoMapper.selectByPrimaryKey((String) id);
    }

    @Override
    public int updateByPrimaryKeySelective(Object o) {
        return companyInfoMapper.updateByPrimaryKeySelective((CompanyInfo) o);
    }

    @Override
    public int updateByPrimaryKey(Object o) {
        return companyInfoMapper.updateByPrimaryKey((CompanyInfo) o);
    }

    @Override
    @Transactional
    public Result saveOrUpdate(CompanyInfo companyInfo) {
        if (companyInfo == null) {
            return Result.newFailInstance("参数缺失");
        }
        String agentComId = LoginUtil.getLoginUser().getCompany().getId();
        String comInfoId = companyInfo.getComInfoId();
        //新增前检查是否已注册
        List<CompanyInfo> oldInfo = companyInfoMapper.selectTheSameCompany(companyInfo);
        if (oldInfo == null || oldInfo.size() == 0) {//未被注册过
            companyInfo.setComInfoId(UUID.randomUUID().toString().replace("-", ""));
            companyInfo.setCreator(LoginUtil.getLoginUserId());
            companyInfo.setCtime(new Date());
            companyInfo.setDelFlag("0");//未删除
            companyInfo.setType("CL");//客户
            companyInfo.setIsAgent("0");//不是代理商
            companyInfo.setIsDrectCust("0");//隐性客户
            this.insertSelective(companyInfo);
            // 建立关系
            agentRefService.insertSelective(new AgentRef(agentComId, companyInfo.getComInfoId()));
        } else {
            String oldComId = null;
            for (CompanyInfo info : oldInfo) {
                boolean theSameCompany = companyInfo.getName().equals(info.getName()) && companyInfo.getUniteCode().equals(info.getUniteCode());
                if (!theSameCompany) {
                    return Result.newFailInstance("请核对填入信息");
                }
                //已经注册过
                if (info.getAgentRefs() != null) {
                    for (AgentRef agentRef : info.getAgentRefs()) {
                        boolean theSameRef = theSameCompany && agentComId.equals(agentRef.getAgentComId());
                        // 已经提交过
                        if (theSameRef && agentRef.getDelFlag().equals("0")) {
                            return Result.newFailInstance("该公司已经提交过了");
                        }
                        // 检查审核状态，包括其他代理的审核
                        if (theSameRef && ("0".equals(agentRef.getAuditStatus()) || "1".equals(agentRef.getAuditStatus()))) {
                            return Result.newFailInstance("该公司已审核通过或审核中");
                        }
                        if (!theSameRef) {
                            oldComId = info.getComInfoId();
                            break;
                        }
                    }
                }
            }
            if (oldComId != null) {
                companyInfo.setComInfoId(oldComId);
                // 建立关系
                agentRefService.insertSelective(new AgentRef(agentComId, companyInfo.getComInfoId()));
            } else {
                return Result.newFailInstance("未知错误");
            }
        }
        return Result.newSuccessInstance("操作成功", companyInfoMapper.selectByPrimaryKey(companyInfo.getComInfoId()));
    }

    /**
     * 查询所有客户资料信息
     *
     * @author han
     */
    public List<CompanyInfo> selCompanyInfoChangeList(SuperCompanyInfo superCompanyInfo) {
        return companyInfoMapper.selCompanyInfoChangeList(superCompanyInfo);
    }

    /**
     * 提交待审核
     */
    @Override
    @Transactional
    public Result recessiveComSubmit(String comInfoId) {
        String agentComId = LoginUtil.getLoginUser().getCompany().getId();
        AuditInfo auditInfo = comAuditService.getAuditInfo(agentComId, comInfoId);
        AgentRef agentRef = agentRefService.getAgentRef(agentComId, comInfoId);
        //检查是否有附件
        List<Attachment> attachments = attachmentService.getAttachmentList(agentRef.getAgentRefId());
        if (attachments == null || attachments.size() == 0) {
            return Result.newFailInstance("必须先上传附件");
        }
        if (auditInfo != null) {
            if ("1".equals(auditInfo.getStatus())) {
                return Result.newFailInstance("该公司已通过审核,无需提交");
            } else if ("0".equals(auditInfo.getStatus())) {
                return Result.newFailInstance("该公司已提交");
            } else if ("2".equals(auditInfo.getStatus())) {
                auditInfo.setDelFlag("1");
                auditInfo.setModifier(LoginUtil.getLoginUserId());
                auditInfo.setMtime(new Date());
                comAuditService.updateByPrimaryKeySelective(auditInfo);
                AuditInfo newAudit = new AuditInfo();
                newAudit.setCinfoAuditId(UUID.randomUUID().toString().replace("-", ""));
                newAudit.setCreator(LoginUtil.getLoginUserId());
                newAudit.setCtime(new Date());
                newAudit.setRelationshipId(agentRef.getAgentRefId());
                newAudit.setAuditor(LoginUtil.getLoginUserId());
                newAudit.setStatus("0");
                newAudit.setDelFlag("0");
                comAuditService.insertSelective(newAudit);
            }
        } else {
            AuditInfo newAudit = new AuditInfo();
            newAudit.setCinfoAuditId(UUID.randomUUID().toString().replace("-", ""));
            newAudit.setCreator(LoginUtil.getLoginUserId());
            newAudit.setCtime(new Date());
            newAudit.setRelationshipId(agentRef.getAgentRefId());
            newAudit.setAuditor(LoginUtil.getLoginUserId());
            newAudit.setStatus("0");
            newAudit.setDelFlag("0");
            comAuditService.insertSelective(newAudit);
        }
        return Result.newSuccessInstance("提交成功");
    }

    /**
     * 通过系统公司 构建公司信息
     *
     * @param sysCom 系统公司
     * @param regCom 系统注册记录
     */
    @Override
    @Transactional
    public void saveComInfoFormSysCompany(Company sysCom, RegisteredCompany regCom) {
        CompanyInfo comInfo = new CompanyInfo();
        comInfo.setName(sysCom.getName());
        comInfo.setComInfoId(sysCom.getId());
        comInfo.setCustomsCode(sysCom.getCom_customs_code());
        comInfo.setUniteCode(sysCom.getCom_code());
        comInfo.setAddress(sysCom.getAddress());
        comInfo.setDelFlag("0");
        comInfo.setStatus("1");
        comInfo.setIsDrectCust("1");
        comInfo.setIsAgent("0");
        comInfo.setType(sysCom.getType());
        comInfo.setCreator(sysCom.getCreator());
        comInfo.setCtime(new Date());
        List<CompanyInfo> oldInfo = companyInfoMapper.selectTheSameCompany2(comInfo);
        if (oldInfo == null || oldInfo.size() == 0) {//未被注册过
            companyInfoMapper.insertSelective(comInfo);
        } else {
            for (CompanyInfo info : oldInfo) {
                if (info.getAgentRefs() != null) {
                    for (AgentRef agentRef : info.getAgentRefs()) {
                        if ("1".equals(agentRef.getDelFlag())) {
                            continue;
                        }
                        if (comInfo.getComInfoId().equals(agentRef.getAgentComId())) {
                            //已存在委托关系
                            return;
                        }
                    }
                }
            }
        }
        // 建立关系，自委托
        AgentRef agentRef = agentRefService.getAgentRef(comInfo.getComInfoId(), comInfo.getComInfoId());
        if (agentRef == null) {
            agentRef = new AgentRef(comInfo.getComInfoId(), comInfo.getComInfoId());
            agentRefService.insertSelective(agentRef);
        }

        if (regCom != null) {
            //联系人
            TGenComContact comContact = new TGenComContact();
            comContact.setComContactId(StringUtils.getUUID());
            comContact.setArefId(agentRef.getAgentRefId());
            comContact.setName(regCom.getCom_link_person());
            comContact.setPhone(regCom.getCom_link_phone());
            tGenComContactMapper.insertSelective(comContact);
        }
    }

    /**
     * 保存上传附件
     */
    @Override
    @Transactional
    public Result uploadCompanyAttachment(MultipartFile file, String comInfoId) {
        String agentComId = LoginUtil.getLoginUser().getCompany().getId();
        AgentRef agentRef = agentRefService.getAgentRef(agentComId, comInfoId);
        if (agentRef == null) {
            return Result.newFailInstance("操作失败，请刷新页面再试");
        } else {
            Attachment attachment = companyAttachmentService.saveUploadFile(file, "companyAttachment");
            if (attachment == null) {
                return Result.newFailInstance("操作失败，请稍候再试");
            }
            CompanyAttachment companyAttachment = new CompanyAttachment();
            companyAttachment.setCreator(LoginUtil.getLoginUserId());
            companyAttachment.setCtime(new Date());
            companyAttachment.setId(attachment.getId());
            companyAttachment.settGId(agentRef.getAgentRefId());
            companyAttachmentService.insertSelective(companyAttachment);
        }
        return Result.newSuccessInstance("上传完成");
    }

    /**
     * 客户类型转换
     *
     * @author han
     */
    @Override
    @Transactional
    public void changeCompanyInfoType(SuperCompanyInfo superCompanyInfo) {
        String KEROLE = "f0fc943258f1574c0158f24df35700ce";//客户角色3.0
        String KEROLEOLD = "402880bd3c09d29e013c09d338400001";//客户角色1.0
        String DLDROLE = "4028803e607938570160793e77cc0000";//待录单角色

        CompanyInfo companyInfo = companyInfoMapper.selectByPrimaryKey(superCompanyInfo.getComInfoId());
        if (companyInfo.getIsAgent().equals("0") && companyInfo.getIsDrectCust().equals("1")) {//更改前是客户
            if (superCompanyInfo.getGsType().equals("1")) {//更改后是代录单人
                // 增加代录单角色
                userService.addRoles4Company(companyInfo.getComInfoId(), DLDROLE);
            } else {
                //todo 转成混合型
                return;
            }
        } else if (companyInfo.getIsAgent().equals("1") && companyInfo.getIsDrectCust().equals("1")) {//更改前是代录单人
            if (superCompanyInfo.getGsType().equals("2")) { //更改后是客户
                userService.deleteRoles(companyInfo.getComInfoId(), DLDROLE);
            } else {
                //todo 其他转换
                return;
            }
        } else {//暂时只支持客户与代录单人之间的转换
            return;
        }
        companyInfoMapper.changeCompanyInfoType(superCompanyInfo);
    }

    /**
     * 根据统一社会信用代码获取公司信息
     */
    @Override
    public CompanyInfo selectByUnitCode(String uniteCode) {
        return companyInfoMapper.selectByUnitCode(uniteCode);
    }

    /**
     * 包含关系id、审核状态
     */
    @Override
    public CompanyInfo selectWithAduit(String comInfoId) {
        String agentId = LoginUtil.getLoginUser().getCompany().getId();
        return companyInfoMapper.selectWithAduit(comInfoId, agentId);
    }
}
